package lee.vioson.ebook.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.rememberAsyncImagePainter
import lee.vioson.ebook.R
import lee.vioson.ebook.data.AppContainer
import lee.vioson.ebook.viewmodels.LauncherViewModel

/**
 *Author:viosonlee
 *Date:2023/6/1
 *DESCRIPTION: launcher page
 */
@Composable
fun LauncherScreen(
    appContainer: AppContainer,
    viewModel: LauncherViewModel = viewModel(factory = LauncherViewModel.factory(appContainer)),
    finishLauncher: () -> Unit
) {
    val cacheAppConfig by viewModel.cacheData.collectAsState()
    val initData by viewModel.initData.collectAsState()
    val state by viewModel.state.collectAsState()

    LaunchedEffect(key1 = state.showLauncher, block = {
        if (!state.showLauncher) {
            finishLauncher.invoke()
        }
    })
    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        val cacheLauncherData = cacheAppConfig?.launcherPic?.first()
        val launcherData = initData?.launcherPic?.first()
        val painter =
            rememberAsyncImagePainter(cacheLauncherData?.imageUrl ?: launcherData?.imageUrl)
        Image(
            painter,
            contentDescription = stringResource(R.string.launcher_icon)
        )
    }
}